<?php


namespace App\User\Services;

use App\BaseService;
use App\User\Models\Archive;
use App\User\Models\Patients;
use Illuminate\Support\Facades\DB;
use App\Handles\CrmRpcHandle;
use App\Common\Services\SmsService;

class PatientsService extends BaseService
{
    use CrmRpcHandle;

    /**
     * @Author   ZhangManMan
     * @DateTime 2021-06-07
     * @describe 获取就诊人列表
     * @version  v1.0
     * @param    array      	    $params               搜索条件集合
     */
    public function getList(array $params, int $limit)
    {
        $fields = ['id', 'u_id', 'relation', 'phone', 'real_name', 'id_card', 'identity_type', 'is_default', 'updated_at'];

        // 获取就诊人列表
        $list = Patients::where('u_id', '=', $params['user_id'])
            ->orderBy('id', 'desc')
            ->paginate($limit);

        foreach ($list as &$items) {
            $items->relation_name = Patients::RELATION_ARR[$items->relation];
            $items->identity_name = Patients::IDENTITY_ARR[$items->identity_type];
        }

        return $list;
    }

    /**
     * User: zhangchaoqun
     * DateTime: 2021/6/9 4:39 下午
     * Describe: 获取就诊人详情
     * Version: V1.0
     * @param array $params
     */
    public function getData(array $params)
    {
        $where = [
            'u_id' => $params['user_id']
        ];

        if (isset($params['is_default']) && $params['is_default'] == Patients::DEFAULT_ON) {
            $where['is_default'] = Patients::DEFAULT_ON;
        } else {
            $where['id'] = $params['id'];
        }

        $data = Patients::where($where)->first();
        if (!$data) {
            throw new \Exception('暂无就诊人');
        }

        $data->relation_name = Patients::RELATION_ARR[$data->relation];

        return $data;
    }

    /**
     * User: zhangchaoqun
     * DateTime: 2021/6/24 1:47 下午
     * Describe: 设置默认就诊人
     * Version: V1.0
     * @param array $params
     * @throws \Exception
     */
    public function setDefault(array $params)
    {
        // 获取就诊人详情
        $data = Patients::find($params['id']);
        if (!$data) {
            throw new \Exception('就诊人不存在');
        }

        // 校验是否越权
        if ($data->u_id != $params['user_id']) {
            throw new \Exception('请勿非法操作');
        }

        try {
            // 判断是否存在其他默认地址
            if ($params['is_default'] == Patients::DEFAULT_ON) {
                $exists = Patients::where('u_id', '=', $params['user_id'])
                    ->where('is_default', '=', Patients::DEFAULT_ON)
                    ->exists();
                if ($exists) {
                    $state = Patients::where('u_id', '=', $params['user_id'])->update([
                        'is_default' => Patients::DEFAULT_OFF
                    ]);
                    if (!$state) {
                        throw new \Exception('更新默认就诊人失败，请联系客服');
                    }
                }
            }

            $data->is_default = $params['is_default'];
            if (!$data->save()) {
                throw new \Exception('设置失败，请联系客服人员');
            }

        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage());
        }
    }
    /**
     * @Author   ZhangManMan
     * @DateTime 2021-06-07
     * @describe 添加就诊人
     * @version  v1.0
     * @param    array        $params            参数集合
     */
    public function addData(array $params)
    {
        // 验证短信验证码
        $smsService = new SmsService();
        $smsService->verifyCode($params['phone'], $params['code'], 'verify');

        // AFTER_API CRM系统此处先查询是否存在认证数据，不存在调用身份认证接口
        $this->userAuthCreate($params['real_name'], $params['id_card'], $params['identity_type']);

        // AFTER_API 接口获取此idcard是否被别人认证
        if ($params['relation'] == Patients::RELATION_SELF) {
            // 判断本人关系是否已添加过
            if (Patients::where('u_id', '=', $params['user_id'])->where('relation', '=', Patients::RELATION_SELF)->exists()) {
                throw new \Exception('已添加过本人身份无需重复添加');
            }
        }

        // 开启事务
        DB::beginTransaction();

        try {
            $addData = [
                'phone' => $params['phone'],
                'real_name' => $params['real_name'],
                'id_card' => $params['id_card'],
                'identity_type' => $params['identity_type'],
                'relation' => $params['relation'],
                'u_id' => $params['user_id'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if (!Patients::insert($addData)) {
                throw new \Exception('添加就诊人失败，请联系客服');
            }

            // AFTER_API 通知用户系统更新认证信息
            if ($params['relation'] == Patients::RELATION_SELF) {
                $userResult = $this->getUserInfoHandle($params['id_card']);
                // 如果不存在已认证用户，则通知认证
                if (empty($userResult)) {
                    $this->userUpdateAuth($params['real_name'], $params['id_card'], $params['user_id']);
                }
            }

            // 提交事务
            DB::commit();
        } catch (\Exception $exception) {
            // 回滚事务
            DB::rollBack();

            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * @Author   ZhangManMan
     * @DateTime 2021-06-07
     * @describe 编辑就诊人信息
     * @version  v1.0
     * @param    array        $params             参数集合
     */
    public function editData(array $params)
    {
        // 获取就诊人数据
        $data = Patients::where('id', '=', $params['id'])->where('u_id', '=', $params['user_id'])->first();
        if (!$data) {
            throw new \Exception('就诊人数据不存在');
        }

        // 校验只允许一个本人关系
        $existSelf = Patients::where('u_id', '=', $params['user_id'])->where('relation', '=', Patients::RELATION_SELF)->exists();
        if ($params['relation'] == Patients::RELATION_SELF && $data->relation != Patients::RELATION_SELF && $existSelf) {
            throw new \Exception('已存在本人关系，不能重复');
        }

        $state = Patients::where('id', '=', $data->id)->update([
            'relation' => $params['relation'],
            'phone' => $params['phone'],
            'is_default' => $params['is_default']
        ]);
        if (!$state) {
            throw new \Exception('保存失败，请联系客服');
        }
    }

    /**
     * @Author   ZhangManMan
     * @DateTime 2021-06-07
     * @describe 删除就诊人信息
     * @version  v1.0
     * @param    array        $params             参数集合
     */
    public function delData(array $params)
    {
        // 此处后期校验是否存在未完成的预约或者复诊订单

        // 获取数据
        $state = Patients::where('id', $params['id'])
            ->where('u_id', $params['user_id'])
            ->delete();

        if (!$state) {
            throw new \Exception('就诊人删除失败，请联系客服');
        }
    }


    /**
     * User: Virus
     * DateTime: 2021/6/24 9:21
     * Describe: 我的就诊记录
     * Version: v1.0.0
     * @throws \Exception
     */
    public function mineRescue($data)
    {
        // 查询患者
        $id = $data['patient_id'];
        $patient = Patients::find($id);
        if(!$patient){
            throw new \Exception('患者不存在！');
        }
        // 查询患者个人档案
        $archive = Archive::where('id_card', $patient->id_card)->first();
        if(!$archive){
            return [];
        }

        $rescues = $archive->hasRescue()->select(['id', 'seek_sn', 'archive_id', 'registration_id', 'status', 'is_first'])
            ->with(['hasRegistrationNum' => function ($table){
                $table->select(['c_id', 'd_id', 'subscribe_date', 'time_start', 'time_end']);
            }])->paginate();

        // 查询诊所
        $clinic_ids = array_unique(data_get($rescues->toArray()['data'], '*.has_registration_num.c_id'));
        $clinic = $this->getClinicListHandle(['ids' => $clinic_ids]);
        $clinic = array_column($clinic, null, 'id');

        // 查询科室
        $department_ids = array_unique(data_get($rescues->toArray()['data'], '*.has_registration_num.d_id'));
        $department = $this->getDepartmentListHandle(['ids' => $department_ids]);
        $department = array_column($department, null, 'id');

        foreach($rescues as &$v){
            $v->clinic = $clinic[$v->hasRegistrationNum->c_id]['name'] ?? '';
            $v->department = $department[$v->hasRegistrationNum->d_id]['name'] ?? '';
        }

        return $rescues;
    }
}
